from PathLength import *
from random import *


def Reverse(Selch, D):
    """
    进化逆转函数,
    :param Selch:被选择的个体
    :param D:各个城市之间的距离矩阵
    :return:进化逆转后的个体
    """
    (row, col) = Selch.shape
    ObjV = PathLength(D, Selch)  # 计算路线长度
    Selch1 = Selch
    for i in range(row):
        r1 = randint(0, col)
        r2 = randint(0, col)
        mininverse = min([r1, r2])
        maxinverse = max([r1, r2])
        if mininverse-1 >= 0:
            Selch1[i][mininverse:maxinverse+1] = Selch1[i][maxinverse:mininverse-1:-1]
        else:
            Selch1[i][mininverse:maxinverse + 1] = Selch1[i][maxinverse::-1]
    ObjV1 = PathLength(D, Selch1)
    index = np.where(ObjV>ObjV1)
    Selch[index[0]] = Selch1[index[0]]
    return Selch